/*********************************************************
*Copyright (c) 2009 Rob Groves. All Rights in Pw
*@des: 异步并发TCP Sever
*@name: Async_Server.cpp
*@author: zhongsx
*@time: 2015-11-16
*********************************************************/

#include "async_server.h"

//#include "../dll/include/StaticLogger.h"
//extern CStaticLogger logger;

////////////////////////////////////////////////////////////////////////////
////////////////////////ASYNC_SERVER////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

async_server::async_server(short port) : io_service_pool_(10), ios_(io_service_pool_.get_io_service()),
	acceptor_(ios_, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
	//内存分配器
	session_pool = boost::make_shared<boost::object_pool<session>>();
	//链接管理
	p_manager = boost::make_shared<session_manager>(ios_, 5);
}

void async_server::init(Read_Msg_CallBack func)
{
	read_func = func;
}

session_manager_ptr async_server::get_session_manager()
{
	return p_manager;
}

void async_server::run()
{
	//使用多个线程 异步监听listen
	//开启监听
	async_accept();
	/*
	//test 使用 coroutine方式监听 listen
	boost::asio::spawn(io_service_pool_.get_io_service(),
		[&](boost::asio::yield_context yield)
		{
			tcp::acceptor acceptor(io_service,
           	tcp::endpoint(tcp::v4(), std::atoi(argv[1])));

          	for (;;)
          	{
            	boost::system::error_code ec;
            	tcp::socket socket(io_service);
            	acceptor.async_accept(socket, yield[ec]);
            	if (!ec) std::make_shared<session>(std::move(socket))->go();
          	}
		}
	);
	*/
	//开启处理线程
	io_service_pool_.start();
}

void async_server::stop()
{
	io_service_pool_.stop();
}

void async_server::async_accept()
{
	//响应客户请求，并等待下个连接
	//session_ptr new_session = boost::make_shared<session>(ios_);

	session_ptr new_session(session_pool->construct(boost::ref(ios_)),
		boost::bind(&boost::object_pool<session>::destroy, session_pool, _1));
	//注册读取数据回调方法
	new_session->RegisterReadMsgCallBack(read_func);
	new_session->RegisterCloseConnCallBack(close_func);
	//
	acceptor_.async_accept(new_session->socket(),
		boost::bind(&async_server::handle_accept, this, new_session,
		boost::asio::placeholders::error));

}

void async_server::handle_accept(boost::shared_ptr<session>& _session,
	const boost::system::error_code& error)
{
	if (!error){
		if (_session != NULL)
		{
			//一些信息
			std::string address = _session->socket().remote_endpoint().address().to_string();
			short port = _session->socket().remote_endpoint().port();
			_session->setaddress(address, port);
			_session->start();

			p_manager->add_session(_session);
		}
		//响应客户请求，并等待下个连接
		async_accept();
	}
	else{
		//logger->Error("server::accept error [%s] ", error.message().c_str());
		return;
	}
}

//注册关闭连接回调
void async_server::RegisterCloseConnCallBack(Close_Conn_CallBack ccc)
{
	close_func = ccc;
}

io_service_pool& async_server::get_servic_pool()
{
	return io_service_pool_;
}
